package com.framework.bdf4j.sysadm.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.framework.bdf4j.comm.Constants;
import com.framework.bdf4j.sysadm.entity.SysIdepermRole;
import com.framework.bdf4j.sysadm.entity.SysRoleMenu;
import com.framework.bdf4j.sysadm.mapper.SysIdepermRoleMapper;
import com.framework.bdf4j.sysadm.mapper.SysRoleMenuMapper;
import com.framework.bdf4j.sysadm.service.SysIdepermRoleService;
import com.framework.bdf4j.sysadm.service.SysRoleMenuService;

import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;

/**
 * <p>
 * 角色菜单表 服务实现类
 * </p>
 *
 */
@Service
@AllArgsConstructor
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService {
	private final CacheManager cacheManager;
	private final SysIdepermRoleService idePermRoleService;

	/**
	 * @param role
	 * @param roleId  角色
	 * @param menuIds 菜单ID拼成的字符串，每个id之间根据逗号分隔
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(value = Constants.MENU_DETAILS, key = "#roleId + '_menu'")
	public Boolean saveRoleMenus(String role, Integer roleId, String menuIds, String idePerms) {
		this.remove(Wrappers.<SysRoleMenu>query().lambda()
				.eq(SysRoleMenu::getRoleId, roleId));
		idePermRoleService.remove(Wrappers.<SysIdepermRole>query().lambda()
				.eq(SysIdepermRole::getRoleId, roleId));
		if (StrUtil.isNotBlank(menuIds)) {
//			return Boolean.TRUE;
			List<SysRoleMenu> roleMenuList = Arrays
					.stream(menuIds.split(","))
					.map(menuId -> {
						SysRoleMenu roleMenu = new SysRoleMenu();
						roleMenu.setRoleId(roleId);
						roleMenu.setMenuId(Integer.valueOf(menuId));
						return roleMenu;
					}).collect(Collectors.toList());
			for (SysRoleMenu sysRoleMenu : roleMenuList) {
				this.save(sysRoleMenu);
			}
//			this.saveBatch(roleMenuList);
		}
		
		if (StrUtil.isNotBlank(idePerms)) {
//			return Boolean.TRUE;
			List<SysIdepermRole> idePermList = Arrays
					.stream(idePerms.split(","))
					.map(ide -> {
						SysIdepermRole roleMenu = new SysIdepermRole();
						roleMenu.setRoleId(Long.valueOf(roleId));
						roleMenu.setIdepermId(Long.valueOf(ide));
						return roleMenu;
					}).collect(Collectors.toList());
			for (SysIdepermRole sysIdepermRole : idePermList) {
				idePermRoleService.save(sysIdepermRole);
			}
//			idePermRoleService.saveBatch(idePermList);
		}

		//清空userinfo
		cacheManager.getCache(Constants.USER_DETAILS).clear();
		return null;
	}
}
